package com.example.store.controller;

import com.example.store.entity.User;
import com.example.store.service.IUserService;
import com.example.store.service.ex.ServiceException;
import com.example.store.util.ResponseResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.util.ArrayList;
import java.util.List;

@RestController   //控制器
@RequestMapping("/users")   //对应前端Form表单路径
public class UserController extends BaseController {
    @Autowired  //调用业务逻辑层接口注解
    private IUserService userService;


    @RequestMapping("/reg")
    public ResponseResult<Void> reg(User user) throws Exception {
        userService.reg (user);
        return new ResponseResult<> (SUCCESS);
    }



    @RequestMapping("/login")
    public ResponseResult<User> login(
            @RequestParam("username") String username,
            @RequestParam("password") String password,
            HttpSession session) {
        // 执行登录验证
        User data = userService.login(username, password);
        // 向Session中封装用户信息
        session.setAttribute("uid", data.getUid());
        session.setAttribute("username", data.getUsername());
        System.out.println (data.toString ());
        // 返回
        return new ResponseResult<>(SUCCESS, data);
    }

    @RequestMapping("/change_password")
    public ResponseResult<Void> changePassword(
            @RequestParam("old_password") String oldPassword,
            @RequestParam("new_password") String newPassword,
            HttpSession session) {
        // 从session中获取uid和username
        Integer uid = getUidFromSession(session);
        String username = session.getAttribute("username").toString();
        // 执行修改密码：service.changePassword(uid,username,oldPassword,newPassword)
        userService.changePassword(uid, username, oldPassword, newPassword);
        // 返回结果
        return new ResponseResult<>(SUCCESS);
    }

    @RequestMapping("/change_info")
    public ResponseResult<Void> changeInfo(User user, HttpSession session) {
        // 封装uid
        Integer uid = getUidFromSession(session);
        user.setUid(uid);
        // 执行修改个人资料
        userService.changeInfo(user);
        // 返回
        return new ResponseResult<>(SUCCESS);
    }

    @GetMapping("/info")
    public ResponseResult<User> getByUid(HttpSession session) {
        // 获取uid
        Integer uid = getUidFromSession(session);
        // 查询用户数据
        User data = userService.getByUid(uid);
        // 返回
        return new ResponseResult<User>(SUCCESS, data);
    }

    //上传图片
    /** * 确定上传文件的名称 */
    private static final String UPLOAD_DIR = "upload";
    /** * 确定上传文件的最大大小 */
    private static final long UPLOAD_MAX_SIZE = 1 * 1024 * 1024;
    /** * 确定允许上传的类型的列表 */
    private static final List<String> UPLOAD_CONTENT_TYPES=
            new ArrayList<> ();
    static {
        UPLOAD_CONTENT_TYPES.add("image/jpeg");
        UPLOAD_CONTENT_TYPES.add("image/png");
        UPLOAD_CONTENT_TYPES.add("image/gif");
        UPLOAD_CONTENT_TYPES.add("image/bmp");
    }
    @PostMapping("/change_avatar")
    public ResponseResult<String> changeAvatar(
            HttpServletRequest request,
            @RequestParam("file") MultipartFile file) throws Exception {
        // 检查文件是否为空
        if (file.isEmpty()) {// 为空：抛出异常：
            throw new Exception();
        }// 检查文件大小
        if (file.getSize() > UPLOAD_MAX_SIZE) {
            // 超出范围
            throw new Exception();
        }
        // 检查文件类型
        String contentType = file.getContentType();
        if (!UPLOAD_CONTENT_TYPES.contains(contentType)) {
            // 类型不符(contains()为false)：抛出异常：
            throw new Exception();
        }
        // 确定文件夹路径：
        request.getServletContext().getRealPath(UPLOAD_DIR);
        String parentPath = request.getServletContext().
                getRealPath(UPLOAD_DIR);
        System.err.print(parentPath);
        // 创建上传文件夹的File对象
        File parent = new File(parentPath);
        // 检查文件夹是否存在，如果不存在，则创建
        if (!parent.exists()) {
            parent.mkdirs();
        }
        // 获取原文件名：
        String originalFilename= file.getOriginalFilename();
        // 从原文件名中得到扩展名
        String suffix = "";
        int beginIndex = originalFilename.lastIndexOf(".");
        if (beginIndex > 0) {
            suffix = originalFilename.substring(beginIndex);
        }

        // 确定文件名：uuid/nanoTime/...
        String filename = System.nanoTime() + suffix;
        // 创建dest对象：
        File dest = new File(parent, filename);
        try {
            file.transferTo(dest);
        }
        catch (Exception e) {
            throw new Exception();
        }
        // 获取uid：
        Integer uid =Integer.valueOf(
                request.getSession().getAttribute("uid").toString());
        // 生成avatar：/UPLOAD_DIR/文件名.扩展名
        String avatar = "/" + UPLOAD_DIR + "/" + filename;
        // 执行更新：
        userService.changeAvatar(uid, avatar);
        userService.changeAvatar(uid, avatar);
        ResponseResult<String> rr= new ResponseResult<String>();
        rr.setState(200);
        rr.setData(avatar);// 返回成功
        return rr;
    }


}
